package com.ocom.company.controller;

import com.ocom.common.constant.CompanyServiceUrl;
import com.ocom.common.constant.UserConstants;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.entity.master.EntityWechatPerInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.utils.StringUtils;
import com.ocom.company.service.MngUserInfoService;
import com.ocom.company.service.WechatPerInfoService;
import com.ocom.company.vo.GetCompanyListByPhoneVo;
import com.ocom.common.vo.company.GetMngUserInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@RestController
public class MngUserInfoController {
    private final Logger log = LoggerFactory.getLogger(MngUserInfoController.class);
    //注入 companyInfoService 业务层
    @Autowired
    private MngUserInfoService mngUserInfoService;

    @Autowired
    private WechatPerInfoService wechatPerInfoService;
    /**
     * 获取管理员用户信息
     * */
    @PostMapping(CompanyServiceUrl.URL_GetMngUserInfo)
    public Result GetMngUserInfo(@Validated @RequestBody GetMngUserInfoVo getMngUserInfoVo){
        return ResultUtil.success(mngUserInfoService.GetMngUserInfo(getMngUserInfoVo.getComId(),getMngUserInfoVo));
    }

    @GetMapping(CompanyServiceUrl.URL_GetMngUserInfoByName)
    public Result<EntityMngUserInfo> GetMngUserInfo(String userName){
        EntityMngUserInfo entityMngUserInfo=mngUserInfoService.GetMngUserInfoByName(userName);
        if(entityMngUserInfo==null){
            return ResultUtil.error(ResultEnum.Err_303);
        }else{
            return ResultUtil.success(entityMngUserInfo);
        }
    }

    /**
     * 获取单位下用户数
     * */
    @GetMapping(CompanyServiceUrl.URL_GetCompanyPersonNum)
    public Result GetCompanyPersonNum(Long comId, String deptId, Long status){
        return ResultUtil.success(mngUserInfoService.GetCompanyPersonNum(comId,deptId,status));
    }

    /**
     * 添加管理员
     * */
    @PostMapping(CompanyServiceUrl.URL_AddCompanyAdminInfo)
    public Result AddCompanyAdminInfo(@Validated @RequestBody EntityMngUserInfo entityMngUserInfo){
        //1.判断userName是否已存在mng_user_info .user_name (调用接口getMngUserInfo) ，不存在则进入下一步，存在则返回错误信息（1.主账号已存在，请重新提交（2008））。
        if ((UserConstants.NOT_UNIQUE.equals(mngUserInfoService.checkUserNameUnique(entityMngUserInfo.getUserName())))){
            return ResultUtil.error(ResultEnum.Err_2008);
        }
        Map<String, Object> map = mngUserInfoService.AddCompanyAdminInfo(entityMngUserInfo);
        return ResultUtil.success(map);
    }

    /**
     * 更新管理员信息
     * */
    @PostMapping(CompanyServiceUrl.URL_UpdateMngUserInfo)
    public Result UpdateMngUserInfo(@Validated @RequestBody EntityMngUserInfo entityMngUserInfo){
        if (StringUtils.isNotEmpty(entityMngUserInfo.getSalt())){
            return ResultUtil.error(ResultEnum.Err_2050);
        }
        Map<String, Object> map = mngUserInfoService.UpdateMngUserInfo(entityMngUserInfo);
        return ResultUtil.success(map);
    }

    /**
     * 3.1.获取管理员信息（getMngUserInfoByOpenid）
     * */
    @GetMapping(CompanyServiceUrl.URL_GetMngUserInfoByOpenid)
    public Result GetMngUserInfoByOpenid(String openid){
        if (StringUtils.isEmpty(openid)){
            return ResultUtil.error(ResultEnum.Err_203);
        }
        List<Object> list = new ArrayList<>();
        //1.先根据传参条件查询表 wechat_per_info 得到集合 list1 ；
        List<EntityWechatPerInfo> wechatPerInfo = wechatPerInfoService.getWechatPerInfo(openid);
        //再根据list1.p_id查询表 mng_user_info as list3（list1.p_id=list3.id）
        for (EntityWechatPerInfo entityWechatPerInfo: wechatPerInfo) {
            HashMap<Object, Object> map = new HashMap<>();

            EntityMngUserInfo entityMngUserInfo = mngUserInfoService.GetMngUserInfo(entityWechatPerInfo.getPId());
            if (entityMngUserInfo == null){
                continue;
            }
            if (entityWechatPerInfo.getPId() == entityMngUserInfo.getId()){
                map.put("id",entityWechatPerInfo.getId());
                map.put("comId",entityWechatPerInfo.getComId());
                map.put("openid",entityWechatPerInfo.getOpenid());
                map.put("appid",entityWechatPerInfo.getAppid());
                map.put("cardId",entityWechatPerInfo.getCardId());
                map.put("pId",entityWechatPerInfo.getPId());
                map.put("agentId",entityMngUserInfo.getComId());
                map.put("userName",entityMngUserInfo.getUserName());
                map.put("password",entityMngUserInfo.getPassword());
                map.put("salt",entityMngUserInfo.getSalt());
                map.put("role",entityMngUserInfo.getRole());
                map.put("createTime",entityMngUserInfo.getCreateTime());
                map.put("updateTime",entityMngUserInfo.getUpdateTime());
                list.add(map);
            }
        }
        return ResultUtil.success(list);
    }

    /**
     * 根据手机号获取管理员用户列表（/getMngUserInfoByPhone）
     * */
    @GetMapping(CompanyServiceUrl.URL_GetMngUserInfoByPhone)
    public Result GetMngUserInfoByPhone(Long comId,String phone){
        log.info("根据手机号获取管理员用户列表请求参数：{{}}",phone);
        EntityMngUserInfo entityMngUserInfo=null;
        try {
            entityMngUserInfo = mngUserInfoService.GetMngUserInfoByPhone(comId,phone);
        }catch (Exception exception){
            log.info("根据手机号获取管理员用户列表失败：{{}}",exception.getMessage());
        }
        if (entityMngUserInfo == null){
            return ResultUtil.error(ResultEnum.Err_303);
        }
        return ResultUtil.success(entityMngUserInfo);
    }

    /**
     * 2.21.手机号获取可管理单位（getCompanyListByPhone）
     * */
    @GetMapping(CompanyServiceUrl.URL_GetCompanyListByPhone)
    public Result GetCompanyListByPhone(String phone){
        log.info("手机号获取可管理单位请求参数：{{}}",phone);
        List<GetCompanyListByPhoneVo> companyListByPhoneVos = new ArrayList<>();
        try {
            companyListByPhoneVos = mngUserInfoService.GetCompanyListByPhone(phone);
        }catch (Exception exception){
            log.info("根据手机号获取管理员用户列表失败：{{}}",exception.getMessage());
        }
        if (companyListByPhoneVos.size() == 0){
            return ResultUtil.error(ResultEnum.Err_303);
        }
        return ResultUtil.success(companyListByPhoneVos);
    }

    /**
     * 3.33通过帐号表获取用户信息
     *
     */

    @GetMapping(CompanyServiceUrl.URL_accountAndRole)
    public Result getUserByNameAndRole(String account,String role){
        return ResultUtil.success( mngUserInfoService.getUserByNameAndRole(account,role));
    }
}
